<template>
    <div>
        <!-- 共用头部组件 -->
        <common-header
            headerTitle="商品详情"
            :hasBack="true"
            :hasHome="true"
        ></common-header>
        <!-- 共用头部组件 -->

        <!-- 共用页面滚动组件 -->
        <common-scroll
            :scrollStyle="scrollStyle"
            :isLoadMore="false"
        >

            <!-- 店主白领标识 -->
            <img
                class="free-get-label"
                src="@/assets/images/goodsDetail/free-get-icon.png"
                v-if="goodsType == 0"
            />
            <!-- 店主白领标识 -->

            <!-- 共用轮播图组件 -->
            <common-swiper
                class="goods-swiper"
                :swiperList="swiperList"
                :swiperHeight="swiperHeight"
                :media="goodsInfo.media"
            ></common-swiper>
            <!-- 共用轮播图组件 -->

            <!-- 商品信息组件 -->
            <goods-info
                :goodsInfo="goodsInfo"
                :goodsType="goodsType"
                :userInfo="userInfo"
                @shareShow="shareShow"
            ></goods-info>
            <!-- 商品信息组件 -->

            <!-- 商品规格组件 -->
            <goods-format
                v-if="goodsType == 0"
                @selectFormat="selectFormat"
                :formatNow="formatNow"
                :goodsNum="goodsNum"
            ></goods-format>
            <!-- 商品规格组件 -->

            <!-- 商品赠品组件 -->
            <!-- <goods-gift @giftSelect="giftShow=true"></goods-gift> -->
            <!-- 商品赠品组件 -->

            <!-- 商品评价组件 -->
            <goods-evaluate
                :commentList="commentList"
                :commentTotal="commentTotal"
                :goodsId="goodsId"
                :goodsType="goodsType"
            ></goods-evaluate>
            <!-- 商品评价组件 -->

            <!-- 商品详情组件 -->
            <goods-details :goodsDetail="goodsDetail"></goods-details>
            <!-- 商品详情组件 -->

        </common-scroll>

        <!-- 商品购买组件 -->
        <goods-buy
            :goodsType="goodsType"
            :goodsId="goodsId"
            :goodsNum="goodsNum"
            :userInfo="userInfo"
            :userData="userData"
            :goodsInfo='goodsInfo'
            :stock="goodsStock"
            @beVip="beVip"
            @goBindPhone="goBindPhone"
            @beMember="beMember"
        >
        </goods-buy>
        <!-- 商品购买组件 -->

        <!-- 分享引导组件 -->
        <share-img
            :shareTips="shareTips"
            :userInfo="userInfo"
            :goodsInfo="goodsInfo"
            :headerImgUrl="headerImgUrl"
            :shareImgUrl="shareImgUrl"
            @closeLoading="shareLoading=false"
            @closeShare="shareTips=false"
        >
        </share-img>
        <!-- 分享引导组件 -->

        <!-- 绑定手机组件 -->
        <bind-phone
            :bindPhone="bindPhone"
            @closeBindPhone="closeBindPhone"
            @updateUserInfo="updateUserInfo"
        ></bind-phone>
        <!-- 绑定手机组件 -->

        <!-- 生成图片loading -->
        <div
            class="loading-bg"
            v-show="shareLoading"
        >
            <img
                class="loading-img"
                src="@/assets/images/home/loading.gif"
            />
            <div class="loading-tips">数据加载中...</div>
        </div>
        <!-- 生成图片loading -->

        <!-- 商品规格选择 -->
        <format-select
            :formatShow="formatShow"
            :formatImg="formatImg"
            :goodsInfo="goodsInfo"
            :goodsNum="goodsNum"
            :formatNow="formatNow"
            :formatList="formatList"
            @formatSelect="formatSelect"
            @minus="minus"
            @add="add"
            @closeFormatSelect="formatShow = false"
        >
        </format-select>
        <!-- 商品规格选择 -->

        <!-- 商品赠品选择 -->
        <gift-select
            :giftShow="giftShow"
            @closeGiftSelect="giftShow = false"
        >
        </gift-select>
        <!-- 商品赠品选择 -->
    </div>
</template>

<script>
import CommonHeader from '@/components/Header'
import CommonScroll from '@/components/Scroll'
import CommonSwiper from '@/components/Swiper'
import GoodsInfo from './components/GoodsInfo'
import GoodsFormat from './components/GoodsFormat'
import FormatSelect from './components/FormatSelect'
import GoodsGift from './components/GoodsGift'
import GiftSelect from './components/GiftSelect'
import ShareImg from './components/ShareImg'
import GoodsEvaluate from './components/GoodsEvaluate'
import GoodsDetails from './components/GoodsDetails'
import GoodsBuy from './components/GoodsBuy'
import BindPhone from '@/components/BindPhone'
import QRCode from 'qrcodejs2'
import html2canvas from 'html2canvas'
import wx from 'weixin-js-sdk'
export default {
    name: 'GoodsDetail',
    components: {
        CommonHeader,
        CommonScroll,
        CommonSwiper,
        GoodsInfo,
        GoodsFormat,
        FormatSelect,
        GoodsGift,
        GiftSelect,
        ShareImg,
        GoodsEvaluate,
        GoodsDetails,
        GoodsBuy,
        BindPhone
    },
    data() {
        return {
            scrollStyle: {
                top: '1.11rem',
                left: '0',
                right: '0',
                bottom: '1.31rem'
            },
            swiperHeight: '100%',
            swiperList: [],
            goodsInfo: '',
            goodsNum: 1,
            goodsStock: 0,
            goodsDetail: '',
            commentList: [],
            commentTotal: 0,
            userInfo: '',
            userData: '',
            goodsType: 0,
            goodsId: '',
            shareTips: false,
            bindPhone: false,
            shareImgUrl: '',
            headerImgUrl: '',
            shareLoading: false,
            headerImgIsReady: false,
            priceImgIsReady: false,
            formatShow: false,
            formatImg: '',
            formatNow: [],
            formatList: [],
            formatNowIds: [],
            giftShow: false
        }
    },
    mounted() {
        this.shareLoading = true
        this.goodsType = this.$route.query.goodsType
        this.goodsId = this.$route.query.goodsId
        this.getGoodsInfo()
        this.getUserInfo()
    },
    methods: {
        formatSelect(data) {
            if (data.bool == 1) {
                this.formatNowIds[data.type] = data.value
                this.getGoodsInfo()
            }
        },
        initFormat() {
            if (this.formatList) {
                this.formatList.forEach(item => {
                    let _index = item.value_list.findIndex(
                        element => element.selected == 1
                    )
                    this.formatNow.push(item.value_list[_index].name)
                    this.formatNowIds.push(item.value_list[_index].id)
                })
            }
        },
        minus() {
            if (this.goodsNum > 1) {
                this.goodsNum--
            }
        },
        add() {
            this.goodsNum++
        },
        getWxConfig() {
            const that = this
            this.axios.post('/api/jsconfig.json').then(res => {
                const data = res.data
                if (data.status == 1) {
                    let routeHost = window.location.origin
                    let routeHref = window.location.href.split('#')[0]
                    let routePath = encodeURIComponent(
                        window.location.href.split('#')[1]
                    )
                    wx.config(data.data)
                    wx.ready(function() {
                        if (typeof wx.updateAppMessageShareData == 'function') {
                            wx.updateAppMessageShareData({
                                title:
                                    '爆款美妆免费领：' + that.goodsInfo.title, // 分享标题
                                desc: that.goodsInfo.title_sub, // 分享描述
                                link: routeHref + '&route=' + routePath, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: that.goodsInfo.imgs[0].title_img, // 分享图标
                                success: function() {
                                    // 设置成功
                                }
                            })
                        } else {
                            wx.onMenuShareAppMessage({
                                title:
                                    '爆款美妆免费领：' + that.goodsInfo.title, // 分享标题
                                desc: that.goodsInfo.title_sub, // 分享描述
                                link: routeHref + '&route=' + routePath, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: that.goodsInfo.imgs[0].title_img, // 分享图标
                                type: '', // 分享类型,music、video或link，不填默认为link
                                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                                success: function() {
                                    // 用户点击了分享后执行的回调函数
                                }
                            })
                        }
                        if (typeof wx.onMenuShareTimeline == 'function') {
                            wx.onMenuShareTimeline({
                                title:
                                    '爆款美妆免费领：' + that.goodsInfo.title, // 分享标题
                                desc: that.goodsInfo.title_sub, // 分享描述
                                link: routeHref + '&route=' + routePath, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: that.goodsInfo.imgs[0].title_img, // 分享图标
                                success: function() {
                                    // 设置成功
                                }
                            })
                        } else {
                            wx.onMenuShareTimeline({
                                title:
                                    '爆款美妆免费领：' + that.goodsInfo.title, // 分享标题
                                desc: that.goodsInfo.title_sub, // 分享描述
                                link: routeHref + '&route=' + routePath, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: that.goodsInfo.imgs[0].title_img, // 分享图标
                                success: function() {
                                    // 用户点击了分享后执行的回调函数
                                }
                            })
                        }
                    })
                } else {
                    this.commonDialog.alert('提示', data.msg)
                }
            })
        },
        getGoodsInfo() {
            let postData = this.qs.stringify({
                id: this.$route.query.goodsId,
                attr_values: this.formatNowIds
            })
            this.axios.post('/api/goods/info.json', postData).then(res => {
                const data = res.data
                if (data.status == 1) {
                    this.shareLoading = false
                    this.goodsInfo = data.data
                    this.formatList = data.data.attr_list
                    this.swiperList = data.data.imgs
                    this.goodsDetail = data.data.content
                    this.goodsStock = data.data.num
                    this.vipGoods = data.data.is_upgrade == '1'
                    this.toBase64(data.data.imgs[0].title_img, 'shareImgUrl')
                    this.getWxConfig()
                    this.formatNow = []
                    this.formatNowIds = []
                    this.goodsId = data.data.id
                    this.formatImg = data.data.imgs[0].title_img
                    this.getCommentList()
                    this.initFormat()
                } else {
                    this.commonDialog.alert('提示', data.msg)
                }
            })
        },
        getCommentList() {
            let postData = this.qs.stringify({
                goods_id: this.goodsId,
                page_size: 5,
                page: 1
            })
            this.axios
                .post('/api/goods/comment_list.json', postData)
                .then(res => {
                    const data = res.data
                    if (data.status == 1) {
                        this.commentList = data.data.list
                        this.commentTotal = data.data.page_info.total
                    } else {
                        this.commonDialog.alert('提示', data.msg)
                    }
                })
        },
        updateUserInfo() {
            this.getUserInfo()
        },
        getUserInfo() {
            this.axios.post('/api/user/data.json').then(res => {
                const data = res.data
                if (data.status == 1) {
                    this.userData = data.data
                } else {
                    this.commonDialog.alert('提示', data.msg)
                }
            })
            this.userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
            if (this.userInfo.face == '') {
                this.headerImgUrl = null
                return
            } else {
                this.toBase64(this.userInfo.face, 'headerImgUrl')
            }
        },
        beVip() {
            sessionStorage.setItem(
                'cart_ids',
                JSON.stringify(this.goodsInfo.id)
            )
            sessionStorage.setItem('cart_goods', JSON.stringify(this.goodsInfo))
            sessionStorage.setItem(
                'cart_price',
                JSON.stringify(this.goodsInfo.price)
            )
            this.$router.push('/vipConfirm')
        },
        shareShow() {
            this.shareLoading = true
            this.shareTips = true
        },
        toBase64(url, target) {
            let postData = this.qs.stringify({
                url: url
            })
            this.axios.post('/api/img/base64.json', postData).then(res => {
                const data = res.data
                if (data.status == 1) {
                    this[target] = data.data
                } else {
                    this.commonDialog.alert('提示', data.msg)
                }
            })
        },
        goBindPhone() {
            this.bindPhone = true
        },
        closeBindPhone() {
            this.bindPhone = false
        },
        beMember() {
            this.$router.push('/experience2')
        },
        selectFormat() {
            this.formatShow = true
        }
    },
    filters: {
        currency(value) {
            return parseFloat(value / 100).toFixed(2)
        }
    }
}
</script>

<style lang="stylus" scoped>
.free-get-label
    position absolute
    top 0.26rem
    right 0.4rem
    width 1.92rem
    z-index 2
.goods-swiper
    background #fff
.loading-bg
    position fixed
    top 0
    left 0
    right 0
    bottom 0
    padding 5% 10%
    background-color rgba(0, 0, 0, 0.9)
    z-index 9
    display flex
    flex-direction column
    align-items center
    justify-content center
    .loading-img
        width 1rem
        height 1rem
    .loading-tips
        width 100%
        margin-top 0.37rem
        font-size 0.38rem
        color #fff
        text-align center
</style>
